package com.jinwei.qunguanjia.web.group.controller;

import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.core.domain.model.LoginUser;
import com.jinwei.qunguanjia.common.core.page.PageDataInfo;
import com.jinwei.qunguanjia.common.core.redis.RedisCache;
import com.jinwei.qunguanjia.common.core.text.CharsetKit;
import com.jinwei.qunguanjia.common.utils.*;
import com.jinwei.qunguanjia.user.dto.*;
import com.jinwei.qunguanjia.user.service.*;
import com.jinwei.qunguanjia.web.group.vo.GroupVO;
import com.jinwei.qunguanjia.web.wechat.service.WxAsyncTemplateMessageService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 群管理相关接口
 *
 * @author yuanzs
 */
@RestController
@RequestMapping("/group")
public class GroupController {

    @Resource
    private GroupService groupService;

    @Resource
    private UserGroupUnlockService userGroupUnlockService;

    @Resource
    private UserService userService;

    @Resource
    private UserIntegralService userIntegralService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private UserTokenService tokenService;

    @Resource
    private GroupLikeService groupLikeService;

    @Resource
    private BlacklistService blacklistService;

    @Resource
    private WxAsyncTemplateMessageService wxAsyncTemplateMessageService;

    /**
     * 新增群
     * @param groupVO 对象
     */
    @PostMapping("/save")
    public Response save(@Validated @RequestBody GroupVO groupVO) {
        GroupDTO groupDTO = new GroupDTO();
        BeanUtils.copyProperties(groupVO, groupDTO);
        groupDTO.setUserId(SystemContextUtils.getUserId());
        groupService.save(groupDTO);
        List<WxMpTemplateData> data = Arrays.asList(
                new WxMpTemplateData("thing1", SystemContextUtils.getUserName()),
                new WxMpTemplateData("time2", DateUtils.getDateTime())
        );
        wxAsyncTemplateMessageService.sendTemplateMessageByOpenId("o_hhj5396JBrpdzKoHdFwe7P3hAI", "tB3SORRpzzOMovuscTMZcRBWMDQKReKUl2fQoRgpe04", data, "");
        return Response.success();
    }

    /**
     * 修改群
     * @param groupVO 对象
     */
    @PutMapping("/update")
    public Response update(@Validated @RequestBody GroupVO groupVO) {
        GroupDTO groupDTO = new GroupDTO();
        BeanUtils.copyProperties(groupVO, groupDTO);
        groupDTO.setGroupStatus("1");
        groupService.update(groupDTO);
        List<WxMpTemplateData> data = Arrays.asList(
                new WxMpTemplateData("thing1", "groupupload:" +SystemContextUtils.getUserName()),
                new WxMpTemplateData("time2", DateUtils.getDateTime())
        );
        wxAsyncTemplateMessageService.sendTemplateMessageByOpenId("o_hhj5396JBrpdzKoHdFwe7P3hAI", "tB3SORRpzzOMovuscTMZcRBWMDQKReKUl2fQoRgpe04", data, "");
        return Response.success();
    }

    /**
     * 删除群
     * @param groupVO 对象
     */
    @DeleteMapping("/delete")
    public Response delete(@Validated @RequestBody GroupVO groupVO) {
        groupService.remove(groupVO.getGroupId());
        return Response.success();
    }

    /**
     * 获取群分页列表
     * @param keyword 关键字
     */
    @GetMapping("/listPage")
    public PageDataInfo<GroupVO> list(String keyword, HttpServletRequest request) throws UnsupportedEncodingException, IllegalAccessException {
        String token = tokenService.getToken(request);
        LoginUser loginUser = redisCache.getCacheObject(tokenService.getTokenKey(token));
        List<String> blacklistUserIdList = new ArrayList<>();
        if (null != loginUser) {
            UserIntegralDTO integralQueryDTO = UserIntegralDTO.builder()
                    .integralType("0")
                    .integralSource("4")
                    .userId(loginUser.getUserId())
                    .createTime("eqDate:"+DateUtils.getDate())
                    .build();
            integralQueryDTO = userIntegralService.get(integralQueryDTO);
            UserDTO userQueryDTO = userService.get(loginUser.getUserId());
            int myIntegral = Integer.parseInt(userQueryDTO.getMyIntegral());
            if (integralQueryDTO == null) {
                UserIntegralDTO integralDTO = UserIntegralDTO.builder()
                        .integralType("0")
                        .integralSource("4")
                        .integralNumber("1")
                        .userId(loginUser.getUserId())
                        .build();
                userIntegralService.save(integralDTO);
                myIntegral = myIntegral + 1;
                UserDTO userDTO = new UserDTO();
                userDTO.setUserId(loginUser.getUserId());
                userDTO.setMyIntegral(String.valueOf(myIntegral));
                userService.update(userDTO);
            }
            BlacklistDTO blacklistDTO = new BlacklistDTO();
            blacklistDTO.setUserId(loginUser.getUserId());
            List<BlacklistDTO> blacklist = blacklistService.list(blacklistDTO);
            for (BlacklistDTO blacklistDTO2 : blacklist) {
                blacklistUserIdList.add(blacklistDTO2.getBlacklistUserId());
            }
        }
        GroupDTO groupDTO = new GroupDTO();
        if (!StringUtils.isEmpty(keyword)) {
            keyword = URLDecoder.decode(keyword,CharsetKit.UTF_8);
            groupDTO.setGroupName(keyword);
            groupDTO.setGroupDesc(keyword);
        }
        groupDTO.setGroupStatus("2");
        groupDTO.setBlacklistUserIdList(blacklistUserIdList);
        PageUtils.startPage();
        PageDataUtil<GroupDTO, GroupVO> pageDataUtil = new PageDataUtil<>();
        return pageDataUtil.transform(groupService.listPage(groupDTO), GroupVO.class);
    }

    /**
     * 获取群详细信息
     * @param groupId 群id
     * @return 群详细信息
     */
    @GetMapping("getInfo")
    public Response<GroupVO> getInfo(@RequestParam String groupId, HttpServletRequest request) throws IllegalAccessException {
        GroupDTO groupDTO = groupService.get(groupId);
        GroupVO groupVO = new GroupVO();
        BeanUtils.copyProperties(groupDTO, groupVO);
        String realName = userService.get(groupDTO.getUserId()).getRealName();
        groupVO.setGroupPoster(realName);
        String token = tokenService.getToken(request);
        LoginUser loginUser = redisCache.getCacheObject(tokenService.getTokenKey(token));
        if (null == loginUser) {
            groupVO.setIsUnlock("0");
            groupVO.setIsLike("0");
            groupVO.setGroupManager("");
            groupVO.setGroupCreator("");
        } else if (loginUser.getUserId().equals(groupDTO.getUserId())) {
            groupVO.setIsUnlock("1");
            GroupLikeDTO groupLikeDTO = new GroupLikeDTO();
            groupLikeDTO.setGroupId(groupId);
            groupLikeDTO.setGroupCommentId("-1");
            groupLikeDTO.setGroupCommentReplyId("-1");
            groupLikeDTO.setUserId(loginUser.getUserId());
            groupLikeDTO = groupLikeService.get(groupLikeDTO);
            if (null == groupLikeDTO) {
                groupVO.setIsLike("0");
            } else {
                groupVO.setIsLike("1");
            }
        } else {
            UserGroupUnlockDTO userGroupUnlockDTO = new UserGroupUnlockDTO();
            userGroupUnlockDTO.setGroupId(groupId);
            userGroupUnlockDTO.setUserId(loginUser.getUserId());
            userGroupUnlockDTO = userGroupUnlockService.get(userGroupUnlockDTO);
            if (null == userGroupUnlockDTO) {
                groupVO.setIsUnlock("0");
                groupVO.setGroupManager("");
                groupVO.setGroupCreator("");
            } else {
                groupVO.setIsUnlock("1");
            }
            GroupLikeDTO groupLikeDTO = new GroupLikeDTO();
            groupLikeDTO.setGroupId(groupId);
            groupLikeDTO.setGroupCommentId("-1");
            groupLikeDTO.setGroupCommentReplyId("-1");
            groupLikeDTO.setUserId(loginUser.getUserId());
            groupLikeDTO = groupLikeService.get(groupLikeDTO);
            if (null == groupLikeDTO) {
                groupVO.setIsLike("0");
            } else {
                groupVO.setIsLike("1");
            }
        }
        return Response.success(groupVO);
    }
    
}
